package servlets;
import dao.Bookdao;
import dao.Cartdao;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.Book;
import bean.Cart;

@WebServlet("/addCart")
public class addCart extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cartdao cartdao = new Cartdao();
        response.setCharacterEncoding("utf-8");
        String isbn = request.getParameter("id");
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("name");

        // 判断返回到哪个界面
        String type = request.getParameter("type");
        if("abook".equals(type)) {
            request.getRequestDispatcher("abook.jsp").forward(request, response);
        }
        if ("cart".equals(type)) {
            request.getRequestDispatcher("cartlist.jsp").forward(request, response);
        }
        Cart cart = cartdao.findById(username, isbn);

        // 获取书本信息
        Bookdao bookdao = new Bookdao();
        Book book = bookdao.getBook(isbn);

        // 如果无该购物项，则创建
        if(cart == null) {
            cart = new Cart(username, isbn, book.getName(), book.getPrice(), 1,
                    book.getLinktoimg());
            cartdao.add(username, cart);
        }
        // 如果存在，数量加1
        else {
            int num = cart.getNum() + 1;
            cartdao.update(username, isbn, num);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
